@echo off

@rem Setup build options
if not exist "%~1" call :output_error 1 "didn't get pa_appname!" & goto :ERR
set pa_appname=%~1
set pa_appdir=%~dp0%pa_appname%
set pa_outdir=%~dp0out\%pa_appname%
set pa_install=0
set pa_error=0
if "%~2"=="install" set pa_install=1
if not exist "%pa_outdir%" mkdir "%pa_outdir%"

@rem Clean out directory
if exist "%pa_outdir%\*.ipk" del /f /q "%pa_outdir%\*.ipk"

@rem Handle plugin build
set pl_outfile=
if exist "%pa_appdir%\plugin" call plugin.cmd %pa_appname% || (call :output_error 2 & goto :ERR)

@rem Handle package IPK file
if not "%pl_outfile%"=="" copy /y "%pa_outdir%\%pl_outfile%" "%pa_appdir%\%pl_outfile%"
call palm-package --exclude="plugin" -o "%pa_outdir%" "%pa_appdir%" || (call :output_error 3 & goto :ERR)
if not "%pl_outfile%"=="" del /f /q "%pa_appdir%\%pl_outfile%"
call :output_finish "package OK!"

@rem Handle IPK install
if %pa_install% equ 0 goto :FINISH
for /f "usebackq" %%i in (`dir /b "%pa_outdir%\*.ipk"`) do call palm-install "%pa_outdir%\%%i" || (call :output_error 4 & goto :ERR)
call :output_finish "install package OK!"

:FINISH
:ERR
exit /b %pa_error%

:output_finish
	echo.
	if not "%~1"=="" echo ***Finish: %~1
	echo.
	set pa_error=0
	goto :eof

:output_error
	set pa_error=%1
	if not "%~2"=="" echo ***Error: %~2
	goto :eof